package hibernate.dao;

import hibernate.entity.ServicoProduto;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ServicoProdutoDAO {
	
	private Session session;
	
	public ServicoProdutoDAO(){
		
	}
	
	public void adiciona(ServicoProduto servicoProduto){		
		
		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();
				
    	try{
			session.save(servicoProduto);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
		    System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}			
	}	

	public void altera(ServicoProduto servicoProduto){		
		
		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();
				
    	try{
			session.update(servicoProduto);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
		    System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}
	}	

	public void remove(ServicoProduto servicoProduto){
		
		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();		
		Transaction transaction = session.beginTransaction();
				
    	try{
			session.delete(servicoProduto);
			transaction.commit();
		} catch(Exception e){
			if(transaction != null)
				transaction.rollback();
		    System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}	
	}	
		
	public List<ServicoProduto> getLista(){
		
		HibernateConnection.buildSessionFactory();
		session = HibernateConnection.openSession();			
		Criteria criteria = session.createCriteria(ServicoProduto.class);		
		List<ServicoProduto> listaServicos = null;
		
    	try{
    		criteria.setFetchMode("produtos", FetchMode.JOIN);
    		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			listaServicos = (List<ServicoProduto>) criteria.list();
		} catch(Exception e){
		    System.out.println("Erro: " + e);
		} finally {
			HibernateConnection.closeSessionFactory();
			session.clear();
			session.close();
		}			
		return listaServicos;
	}
}
